package com.heima.article.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("test")
public class TestController {
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private IApArticleService apArticleService;
    @Autowired
    private IApArticleContentService contentService;
    @Autowired
    private Configuration configuration;
    @GetMapping("/html/{id}")
    public ResponseResult createHtml(@PathVariable("id") Long id) throws IOException, TemplateException {
        //根据id查询文章的数据
        ApArticle apArticle = apArticleService.getById(id);
        //查询文章内容表
        LambdaQueryWrapper<ApArticleContent> query=new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId,id);
        ApArticleContent apArticleContent=contentService.getOne(query);
        //使用freemarker生成html文件
        //获取模板
        Template template = configuration.getTemplate("article.ftl");
        //准备数据
        Map<String,Object> map=new HashMap<>();
        map.put("content", JSON.parseArray(apArticleContent.getContent()));
        //合并模板和数据
        Writer writer=new StringWriter();
        template.process(map,writer);
        //将文件存到minio表中
        String name=id+".html";
        //构建输入流
        InputStream is=new ByteArrayInputStream(writer.toString().getBytes());
        String url = minIOService.upload(name, is, "text/html");
        //将minion返回的地址保存到文章表中
        apArticle.setStaticUrl(url);
        apArticleService.updateById(apArticle);
        return ResponseResult.okResult();
    }
}
